<template>
  <a-modal :width="1200" v-model:visible="showAddKeyword" title="批量添加到关键词投放" title-align="start" :mask-closable="false" :on-before-ok="submitData" :ok-loading="submitLoading" @cancel="closedDialog">
    <a-table class="table-normal-line" ref="tableRef" :data="addList" :scroll="{ x: '1400px', y: 'calc(84vh - 200px)' }" size="mini" :bordered="false" :pagination="false">
      <template #columns>
        <a-table-column :width="180" data-index="searchTerm" fixed="left">
          <template #title>
            <p>
              <span class="warningColor">*</span>
              <span>买家搜索词</span>
            </p>
          </template>
          <template #cell="{ record }">
            <a-input v-model="record.searchTerm" size="small" style="width: 160px" placeholder="" @change="getKeywordRecommendation" />
          </template>
        </a-table-column>
        <a-table-column :width="140" data-index="matchType">
          <template #title>
            <p>
              <span class="warningColor">*</span>
              <span>匹配类型</span>
            </p>
          </template>
          <template #cell="{ record, rowIndex }">
            <div class="flex-c">
              <a-select size="small" v-model="record.matchType" style="width: 100px" placeholder="匹配类型" @change="getKeywordRecommendation">
                <a-option v-for="(matchType, i) in matchTypeList" :key="i" :value="matchType.value" :label="matchType.label" />
              </a-select>
              <a-button size="small" style="margin-left: 4px" class="gray-outline" v-if="rowIndex === 0" @click="setGlobal(record, 'matchType')">
                <template #icon>
                  <icon-double-down />
                </template>
              </a-button>
            </div>
          </template>
        </a-table-column>
        <a-table-column :width="240" data-index="shopId">
          <template #title>
            <p>
              <span class="warningColor">*</span>
              <span>店铺</span>
            </p>
          </template>
          <template #cell="{ record, rowIndex }">
            <div class="flex-c">
              <a-select size="small" v-model="record.shopId" placeholder="请选择店铺" @change="changeShop(record)" style="width: 200px" :trigger-props="{ autoFitPopupMinWidth: true }" allow-search>
                <a-option v-for="(shopInfo, i) in shopList" :key="i" :value="shopInfo.id" :label="shopInfo.shopName" />
              </a-select>
              <a-button size="small" style="margin-left: 4px" class="gray-outline" v-if="rowIndex === 0" @click="setGlobal(record, 'shopId')">
                <template #icon>
                  <icon-double-down />
                </template>
              </a-button>
            </div>
          </template>
        </a-table-column>
        <a-table-column :width="240" data-index="campaignId">
          <template #title>
            <p>
              <span class="warningColor">*</span>
              <span>广告活动</span>
            </p>
          </template>
          <template #cell="{ record, rowIndex }">
            <div class="flex-c">
              <a-select v-model="record.campaign" placeholder="请选择活动" value-key="campaignId" :fallback-option="fallback" style="width: 200px" :trigger-props="{ autoFitPopupMinWidth: true }" @popup-visible-change="openCampaignSelect($event, record)" allow-search @change="changeCampaign(record)" @search="searchCampaignList($event, record)" :filter-option="false">
                <a-option v-for="(campaign, i) in record.campaignList" :key="i" :value="campaign" :label="campaign.campaignName" />
              </a-select>
              <a-button size="small" style="margin-left: 4px" class="gray-outline" v-if="rowIndex === 0" @click="setGlobal(record, 'campaign')">
                <template #icon>
                  <icon-double-down />
                </template>
              </a-button>
            </div>
          </template>
        </a-table-column>
        <a-table-column :width="240" data-index="adGroupId">
          <template #title>
            <p>
              <span class="warningColor">*</span>
              <span>广告组</span>
            </p>
          </template>
          <template #cell="{ record, rowIndex }">
            <div class="flex-c">
              <a-select v-model="record.adGroup" placeholder="请选择广告组" value-key="adGroupId" @change="getKeywordRecommendation" :fallback-option="fallback" :trigger-props="{ autoFitPopupMinWidth: true }" style="width: 200px" allow-search @popup-visible-change="openAdGroupSelect($event, record)" @search="searchAdGroupList($event, record)" :filter-option="false">
                <a-option v-for="(adGroup, i) in record.adGroupList" :key="i" :value="adGroup" :label="adGroup.adGroupName" />
              </a-select>
              <a-button size="small" style="margin-left: 4px" class="gray-outline" v-if="rowIndex === 0" @click="setGlobal(record, 'adGroup')">
                <template #icon>
                  <icon-double-down />
                </template>
              </a-button>
            </div>
          </template>
        </a-table-column>
        <a-table-column :width="80" data-index="adviceBid" title="建议竞价(USD)">
          <template #cell="{ record }">
            <p class="highlight">{{ getAdviceBid(record, 'rangeMedian') }}</p>
            <p>{{ getAdviceBid(record, 'rangeStart') }}~{{ getAdviceBid(record, 'rangeEnd') }}</p>
          </template>
        </a-table-column>
        <a-table-column :width="80" data-index="adType" title="活动类型">
          <template #cell="{ record }">
            <p v-if="record.campaign && record.campaign.adType">{{ AdTypes[record.campaign.adType] }}</p>
            <p v-else>--</p>
          </template>
        </a-table-column>
        <a-table-column :width="150" data-index="bid">
          <template #title>
            <p>
              <span class="warningColor">*</span>
              <span>关键词竞价(USD)</span>
            </p>
          </template>
          <template #cell="{ record, rowIndex }">
            <div class="flex-c">
              <a-input-number :min="0" :precision="2" v-model="record.bid" size="small" style="width: 100px" placeholder="" />
              <a-button size="small" style="margin-left: 4px" class="gray-outline" v-if="rowIndex === 0" @click="setGlobal(record, 'bid')">
                <template #icon>
                  <icon-double-down />
                </template>
              </a-button>
            </div>
          </template>
        </a-table-column>
        <a-table-column :width="80" data-index="adviceBid" title="操作" fixed="right">
          <template #cell="{ record, rowIndex }">
            <a-space>
              <a-popconfirm content="确定是否移除?" @ok="addList.splice(rowIndex, 1)" type="error">
                <a-button type="text">移除</a-button>
              </a-popconfirm>
              <a-button type="text" @click="copyData(rowIndex, record)">复制</a-button>
            </a-space>
          </template>
        </a-table-column>
      </template>
    </a-table>
  </a-modal>
</template>
<script lang="ts" setup>
  import { ref, onMounted, PropType } from 'vue'
  import { Message } from '@arco-design/web-vue'
  import { batchCreateKeywordBySearchTerm, getAllCampaignList, getAllAdGroupList, keywordRecommendation } from '@/api/advert'
  import { AdTypes } from '../../types'

  const emit = defineEmits(['closed', 'success'])
  const props = defineProps({
    isShow: {
      type: Boolean,
      default: false,
    },
    shopList: {
      type: Array as PropType<Array<any>>,
      default: () => [],
    },
    list: {
      type: Array,
      default: () => [],
    },
  })
  onMounted(() => {
    setDefaultList()
  })

  const showAddKeyword = ref(props.isShow)
  const submitLoading = ref(false)
  const addList = ref<Array<any>>([])
  const bidMap = ref<any>({})
  const matchTypeList = [
    {
      label: '精确匹配',
      value: 'EXACT',
    },
    {
      label: '词组匹配',
      value: 'PHRASE',
    },
    {
      label: '广泛匹配',
      value: 'BROAD',
    },
  ]

  function setDefaultList() {
    let list = JSON.parse(JSON.stringify(props.list))
    list.forEach((el: any) => {
      el.matchType = null
      el.bid = null
      el.campaignList = []
      el.adGroupList = []
      if (!props.shopList.find((item: any) => item.id === el.shopId)) {
        el.shopId = null
        el.campaign = null
        el.adGroup = null
      } else {
        if (el.campaignId) {
          el.campaign = {
            campaignId: el.campaignId,
            campaignName: el.campaignName,
            adType: el.adType,
          }
          el.campaignList = [el.campaign]
        }
        if (el.adGroupId) {
          el.adGroup = {
            adGroupId: el.adGroupId,
            adGroupName: el.adGroupName,
          }
          el.adGroupList = [el.adGroup]
        }
      }
    })
    addList.value = list
    getKeywordRecommendation()
  }

  function fallback(value: any) {
    return value
  }
  // 获取建议竞价
  async function getKeywordRecommendation() {
    bidMap.value = {}
    let list: Array<any> = []
    addList.value.forEach((el: any) => {
      if (el.matchType && el.searchTerm && el.shopId && el.campaign?.campaignId && el.adGroup?.adGroupId) {
        let otherObj =
          el.campaign.adType == 'SPONSORED_PRODUCTS'
            ? {
                spKeywordRecommendationType: 'KEYWORDS_FOR_ADGROUP',
                sortDimension: 'CONVERSIONS',
              }
            : {}
        list.push({
          shopId: el.shopId,
          shopKeywordInfo: {
            adGroupId: el.adGroup.adGroupId,
            adType: el.campaign.adType,
            campaignId: el.campaign.campaignId,
            keywordInfoBOs: [
              {
                keyword: el.searchTerm,
                matchType: el.matchType,
              },
            ],
            maxRecommendations: 0,
            ...otherObj,
          },
        })
      }
    })
    if (!list.length) return
    const res: any = await keywordRecommendation(list)
    let resList = res?.data || []
    resList.forEach((el: any) => {
      el.keywordInfos?.forEach((item: any) => {
        let dataKey = el.shopId + el.campaignId + el.adGroupId + item.keyword + item.matchType
        bidMap.value[dataKey] = item
      })
    })
  }
  // 显示建议竞价
  function getAdviceBid(row: any, key: string) {
    let dataKey = row.shopId + row.campaign?.campaignId + row.adGroup?.adGroupId + row.searchTerm + row.matchType
    return bidMap.value[dataKey]?.[key] || '--'
  }
  // 批量
  function setGlobal(row: any, key: string) {
    addList.value.forEach((el: any) => {
      if (key == 'shopId') {
        // 批量设置店铺的时候如果和原本的不一致  则需要清空选中的活动和组
        if (el.shopId != row.shopId) {
          el.campaign = null
          el.adGroup = null
        }
        el.shopId = row.shopId
      } else if (key == 'campaign') {
        // 批量设置活动的时候如果和原本的不一致  则需要清空选中组
        if (el.campaign?.campaignId != row.campaign?.campaignId) {
          el.adGroup = null
        }
        el.campaignList = JSON.parse(JSON.stringify(row.campaignList))
        el.campaign = JSON.parse(JSON.stringify(row.campaign))
        // 活动一致时，需要保证店铺也是一致的
        el.shopId = row.shopId
      } else if (key == 'adGroup') {
        el.shopId = row.shopId
        el.campaignList = JSON.parse(JSON.stringify(row.campaignList))
        el.campaign = JSON.parse(JSON.stringify(row.campaign))
        el.adGroupList = JSON.parse(JSON.stringify(row.adGroupList))
        el.adGroup = JSON.parse(JSON.stringify(row.adGroup))
      } else {
        el[key] = row[key]
      }
    })
    if (key != 'bid') {
      getKeywordRecommendation()
    }
  }
  // 单个切换店铺，当前数据的广告活动等信息都需要清空
  function changeShop(row: any) {
    row.campaign = null
    row.adGroup = null
    getKeywordRecommendation()
  }
  // 单个切换广告活动,当前数据的广告组信息需要清空
  function changeCampaign(row: any) {
    row.adGroup = null
    getKeywordRecommendation()
  }
  // 打开活动下拉框
  async function openCampaignSelect(val: boolean, row: any) {
    if (val) {
      row.campaignList = await getCampaignList(row.campaign?.campaignName, row.shopId)
    }
  }
  // 输入关键字查询活动
  async function searchCampaignList(val: string, row: any) {
    row.campaignList = await getCampaignList(val, row.shopId)
  }
  // 打开广告组下拉框
  async function openAdGroupSelect(val: boolean, row: any) {
    if (val) {
      row.adGroupList = await getAdGroupList(row.adGroup?.adGroupName, row)
    }
  }
  // 输入关键字查询广告组
  async function searchAdGroupList(val: string, row: any) {
    row.adGroupList = await getAdGroupList(val, row)
  }

  // 获取广告活动列表
  async function getCampaignList(val?: string, shopId?: string) {
    const res: any = await getAllCampaignList({
      search: val,
      shopId: shopId,
    })
    return res?.data || []
  }
  // 获取广告组列表
  async function getAdGroupList(val?: string, row?: any) {
    const res: any = await getAllAdGroupList({
      search: val,
      shopId: row.shopId,
      campaignId: row.campaign?.campaignId,
    })
    return res?.data || []
  }
  // 复制
  function copyData(i: number, row: any) {
    addList.value.splice(i, 0, JSON.parse(JSON.stringify(row)))
  }
  // 关闭
  function closedDialog() {
    showAddKeyword.value = false
    emit('closed')
  }

  // 创建关键词
  async function submitData() {
    let flag = true
    addList.value.forEach((el: any) => {
      if (!el.searchTerm || !el.shopId || !el.matchType || !el.campaign?.campaignId || !el.adGroup?.adGroupId || !el.bid) {
        flag = false
      }
    })
    if (!flag) {
      Message.error('请完善必填信息')
      return false
    }
    let list = addList.value.map((el: any) => {
      return {
        adGroupId: el.adGroup?.adGroupId,
        adType: el.campaign?.adType,
        campaignId: el.campaign?.campaignId,
        matchType: el.matchType,
        searchTerm: el.searchTerm,
        shopId: el.shopId,
        bid: el.bid,
      }
    })
    const res: any = await batchCreateKeywordBySearchTerm(list)
    if (!res) return false
    Message.success('添加成功')
    emit('success')
    closedDialog()
  }
</script>
<style lang="less" scoped></style>
